<template>
  <div class="word-preview">
    <div class="sidebar">
      <ul>
        <li v-for="(item, index) in toc" :key="index">
          <!-- @click="jumpToSection(index)" -->
          <a :href="item.anchor">{{ item.title }}</a>
        </li>
      </ul>
    </div>
    <div class="content" ref="content">
      <!-- <div v-html="docContent"></div> -->
    </div>
  </div>
</template>

<script>
import mammoth from 'mammoth';

export default {
  data() {
    return {
      docContent: null,
      toc: [],
      currentSection: ''
    };
  },
  mounted() {
    this.loadDocument();
  },
  methods: {
    async loadDocument() {
      try {
        const response = await fetch('/1.docx');
        const arrayBuffer = await response.arrayBuffer();
        const result = await mammoth.convertToHtml({arrayBuffer });
        this.docContent = result.value;
        
        this.parseDocument();
      } catch (error) {
        console.error('Error loading document:', error);
      }
    },
    parseDocument() {
      const parser = new DOMParser();
      const doc = parser.parseFromString(this.docContent, 'text/html');
      // console.log('doc:',this.docContent,doc);
      // this.docContent = doc
      const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
      // console.log('headings',headings);
      this.toc = Array.from(headings).map((heading, index) => {
        heading.setAttribute('id',`section-${index}`) 
        return {
        title: heading.textContent,
        anchor: `#section-${index}`
      }
      
      } );
      this.$nextTick(()=> {
        document.getElementsByClassName('content')[0].appendChild(doc.body)
      })
      // this.$refs.content.appendChild(doc)
    },
    jumpToSection(index) {
      const anchor = `section-${index}`;
      const targetElement = this.$refs.content.querySelector(`[id="${anchor}"]`);
      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.word-preview {
  display: flex;
  height: calc(100vh - 85px);
}

.sidebar {
  width: 30%;
  padding: 1rem;
  border-right: 1px solid #ccc;
  overflow: auto;
  height: 100%;
}

.content {
  width: 70%;
  padding: 1rem;
  overflow: auto;
  height: 100%;
}

h1, h2, h3, h4, h5, h6 {
  margin: 0;
}

a {
  cursor: pointer;
}
</style>
